<style scoped lang="less">
.area-tree {
    height: 100%;
    height: calc(100% - 38px);
    overflow: auto;
}
</style>
<template>
    <div class="area-tree" v-loading="loading">
        <el-tree
            :data="data"
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
            unselectable="on"
            :default-expand-all="true"
            :expand-on-click-node="false"
            :indent="36"
            @node-contextmenu="showContextMenu"
        >
            <div
                class="tree-node"
                :class="{ active: activeNodeId == node.id }"
                slot-scope="{ node, data }"
            >
                {{ data.name }}
            </div>
        </el-tree>
        <div class="text-center" v-if="data.length == 0">
            <el-button type="green" @click="newAction" :disabled="!$store.getters.hasEditPermission"
                >添加分区</el-button
            >
        </div>
        <ul
            class="context-menu"
            v-if="menuVisible"
            :style="{ left: menuX + 'px', top: menuY + 'px' }"
        >
            <li v-for="(item, index) in menuList" :key="index" @click="menuHandler(item.handler)">
                {{ item.name }}
            </li>
        </ul>
        <!-- 添加/编辑 start -->
        <el-dialog
            :title="newModalTitle"
            :visible.sync="newModalVisible"
            v-if="newModalVisible"
            width="400px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            destroy-on-close
            append-to-body
        >
            <el-form ref="newForm" :model="newForm" label-width="120px">
                <el-form-item label="父级：" v-if="!newForm.id">{{
                    !activeData || activeData.name == "全部分区" ? "无" : activeData.name
                }}</el-form-item>
                <el-form-item
                    label="名称："
                    prop="name"
                    :rules="[{ required: true, message: '请输入名称', trigger: 'change' }]"
                >
                    <el-input
                        placeholder="请输入"
                        type="text"
                        v-model.trim="newForm.name"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button type="cancel" @click="newModalVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    :loading="adding"
                    @click="submitAction"
                    :disabled="!$store.getters.hasEditPermission"
                    >确定</el-button
                >
            </div>
        </el-dialog>
        <!-- 添加/编辑 end -->
    </div>
    <!-- render-content="renderContent" -->
</template>
<script>
import { mapState } from "vuex"
export default {
    name: "ParittionTree",
    props: {
        businessId: {
            type: String,
            default: "",
        },
        isEditable: {
            type: Boolean,
            default: false,
        },
    },
    computed: {
        ...mapState(["scale"]),
        defaultExpandedKeys() {
            // if (this.data.length > 0) {
            // 	let ids = [];
            // 	let provs = this.data[0].regions;
            // 	let citys = [];
            // 	provs.forEach((item, index) => {
            // 		citys = [...citys, ...item.regions];
            // 	});
            // 	ids = citys.map((item) => item.id);
            // 	return ids;
            // }
            return []
        },
    },
    watch: {},
    data() {
        return {
            loading: false,
            data: [],
            defaultProps: {
                children: "childList",
                label: "name",
            },
            activeNodeId: "",

            activeData: null,
            activeLevel: 0,
            menuList: [],
            menuVisible: false,
            menuX: 0,
            menuY: 0,
            newModalTitle: "新建",
            newModalVisible: false,
            newForm: {},
            adding: false,
        }
    },
    created() {
        this.getTreeData()
    },
    mounted() {
        document.addEventListener("click", this.clickDom, false)
    },
    beforeDestroy() {
        document.removeEventListener("click", this.clickDom, false)
    },
    methods: {
        getTreeData() {
            this.loading = true
            this.$get("/check/maintenance/partitionTreeList", { businessId: this.businessId }).then(
                (res) => {
                    this.loading = false
                    // res.data.name = "中国";
                    if (res.data.childList.length > 0) {
                        this.data = [res.data]
                        // this.$emit("nodeClick", {id: 0});
                    } else {
                        this.data = []
                    }
                },
                (err) => {
                    this.loading = false
                    if (err.msg) {
                        this.$message.error(err.msg)
                    }
                }
            )
        },
        getAllAreaName(node, names) {
            names.push(node.data.name)
            if (node.parent && node.data.pid != 0) {
                this.getAllAreaName(node.parent, names)
            }
        },
        handleNodeClick(data, node, n) {
            this.activeNodeId = node.id
            if (data.id == 0) {
                this.$emit("nodeClick", { id: 0 })
            } else {
                this.$emit("nodeClick", data)
            }
            this.hideMenu()
        },

        showContextMenu(event, data, node, el) {
            if (!this.isEditable) return
            let menuList = []
            // this.hasPermission('006002001')
            if (this.$store.getters.hasEditPermission) {
                if (node.level < 3) {
                    menuList.push({
                        name: "新建下级",
                        handler: "new",
                    })
                }
                if (node.level > 1) {
                    menuList.push({
                        name: "编辑",
                        handler: "edit",
                    })
                    menuList.push({
                        name: "删除",
                        handler: "delete",
                    })
                }
            }
            // if(this.hasPermission('006002002')){
            // 	menuList.push({
            // 		name: "编辑",
            // 		handler: "edit",
            // 	})
            // }
            // if(this.hasPermission('006002003')){
            // 	menuList.push({
            // 		name: '删除',
            // 		handler: 'delete'
            // 	})
            // }
            this.menuList = menuList
            this.activeNode = node
            this.activeData = node.data
            this.activeLevel = node.level
            this.menuVisible = true
            this.menuX = event.clientX
            this.menuY = event.clientY
        },
        menuHandler(type) {
            this.menuVisible = false
            if (type == "new") {
                this.newAction()
            } else if (type == "edit") {
                this.editAction()
            } else if (type == "delete") {
                this.deleteRegion()
            }
        },
        hideMenu() {
            this.menuVisible = false
            // this.activeNode = null
        },
        clickDom() {
            this.hideMenu()
        },
        newAction() {
            this.newModalTitle = "新建分区"
            this.newForm = {}
            if (!this.activeData || this.activeData.id == 0) {
                this.newForm.pid = "0"
                this.newForm.allid = ""
                this.newForm.level = 1
            } else {
                this.newForm.pid = this.activeData.id
                this.newForm.allid = this.activeData.id
                this.newForm.level = this.activeLevel
            }

            this.newForm.businessId = this.businessId
            this.newModalVisible = true
            if (this.$refs["newForm"]) {
                this.$refs["newForm"].resetFields()
            }
        },

        editAction() {
            this.newModalTitle = "编辑分区"
            this.newForm = {
                id: this.activeData.id,
                name: this.activeData.name,
            }
            this.newModalVisible = true
        },
        deleteRegion() {
            this.showConfirm("确定删除该分区吗？", () => {
                this.deleting = true
                this.$post("/check/maintenance/partitionDel", {
                    id: this.activeData.id,
                }).then(
                    (res) => {
                        this.deleting = false
                        this.$message.success("删除成功")
                        this.removeNode(this.activeNode, this.activeData)
                    },
                    (err) => {
                        this.deleting = false
                        this.$message.error(err.msg)
                    }
                )
            })
        },
        removeNode(node, data) {
            const parent = node.parent
            const children = parent.data.childList || parent.data
            const index = children.findIndex((d) => d.id === data.id)
            children.splice(index, 1)
        },
        submitAction() {
            this.$refs["newForm"].validate((valid) => {
                if (valid) {
                    this.adding = true
                    let params = Object.assign({}, this.newForm)
                    let url = ""
                    let isEdit = !!this.newForm.id
                    this.$post("/check/maintenance/partitionAddOrUpdate", params).then(
                        (res) => {
                            this.adding = false
                            this.$message.success("保存成功")
                            this.newModalVisible = false
                            this.getTreeData()
                            // if(isEdit){
                            // 	this.activeData.name= this.newForm.name
                            // }else{
                            // 	if (!this.activeData.childList) {
                            // 		this.$set(this.activeData, 'childList', []);
                            // 	}
                            // 	this.activeData.childList.push(res.data);
                            // }
                        },
                        (error) => {
                            this.adding = false
                            this.$message.error(error.msg)
                        }
                    )
                } else {
                    return false
                }
            })
        },
    },
}
</script>
